package com.lc.zpyh.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.hjq.toast.ToastUtils;
import com.lc.zpyh.R;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.supermarket.ShopDetailsActivity;
import com.lc.zpyh.util.BigDecimalUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.RecyclerView;


/**
 * @Title：
 * @Description：
 * @Author：huqinghan(19044311)
 * @Date：2021/3/24
 */
public class BusinessAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    JSONArray jsa;
    Context mContext;
    String merchantid;
    String cartcount;
    String shopname;
    String cardId;
    private OnAddCartrListener onAddCartrListener;
    private int price;

    public BusinessAdapter(Context context){
        this.mContext = context;

    }

    public void setData(JSONArray jsa,String merchantid,String shopname,String cartcount ,String cardId){
        this.jsa = jsa;
        this.merchantid = merchantid;
        this.shopname = shopname;
        this.cardId=cardId;
        this.cartcount=cartcount;
        notifyDataSetChanged();
    }


    public int getItemIndexForGroup(int index){
        int num = 0;
        for (int i = 0; i < jsa.length(); i++) {
            if (isGroup(i)){
                num++;
            }
            if (num == index){
                return i;
            }
        }
        return 0;
    }

    public int getGroupIndex(int index){
        int num = 0;
        for (int i = 0; i < index; i++) {
            if (isGroup(i)){
                num++;
            }
        }
        return num;
    }


    public boolean isGroup(int position){

            JSONObject jo = jsa.optJSONObject(position);
            return jo.has("_isGroup") && jo.optBoolean("_isGroup");

    }
    public void setChildGroup(int position, boolean flag){
        JSONObject jo = jsa.optJSONObject(position);
        try {
            jo.putOpt("_isChildGroup", flag);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public boolean isChildGroup(int position){
        JSONObject jo = jsa.optJSONObject(position);
        return jo.has("_isChildGroup") && jo.optBoolean("_isChildGroup");
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        if (viewType == 0){
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_test_group, viewGroup, false);
            ItemHolder holder = new ItemHolder(view);
            holder.titile = view.findViewById(R.id.header_title);
            return holder;
        }else {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_test_child, viewGroup, false);
            ItemChildHolder holder = new ItemChildHolder(view);
            holder.name = view.findViewById(R.id.goods);
            holder.tv_yueshou = view.findViewById(R.id.tv_yueshou);
            holder.tv_xianjia = view.findViewById(R.id.tv_xianjia);
            holder.tv_yuanjia = view.findViewById(R.id.tv_yuanjia);
            holder.img_dianpu = view.findViewById(R.id.img_dianpu);
            holder.fl_reduce = view.findViewById(R.id.fl_reduce);
            holder.fl_add = view.findViewById(R.id.fl_add);
            holder.tv_number = view.findViewById(R.id.tv_number);
            holder.rl_top = view.findViewById(R.id.rl_top);
            holder.headerTitle = view.findViewById(R.id.header_title);
            holder.rl_status = view.findViewById(R.id.rl_status);
            holder.ll_number = view.findViewById(R.id.ll_number);
            holder.tv_buhuo = view.findViewById(R.id.tv_buhuo);
            return holder;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if (viewHolder instanceof ItemHolder) {
            ItemHolder holder = (ItemHolder) viewHolder;
            JSONObject jo = getItem(position);
//            头布局的名字
            holder.titile.setText(jo.optString("classifyName"));
        } else if (viewHolder instanceof ItemChildHolder) {
            ItemChildHolder holder = (ItemChildHolder) viewHolder;
            JSONObject jo = getItem(position);
            Glide.with(mContext)
                    .load(IntentKey.CAR_IMAGE+jo.optString("img")).apply(new RequestOptions().placeholder(R.mipmap.zhanweiicon01).error(R.mipmap.zhanweiicon01))
                    .into((ImageView) holder.img_dianpu);
            holder.name.setText(jo.optString("commodityName"));
            holder.tv_yueshou.setText("月售"+jo.optString("sales") + "仅剩"+jo.optInt("inventory")+"份");

            if (jo.optInt("inventory")==0){
                holder.tv_buhuo.setVisibility(View.VISIBLE);
                holder.ll_number.setVisibility(View.GONE);
            }else {
                holder.tv_buhuo.setVisibility(View.GONE);
                holder.ll_number.setVisibility(View.VISIBLE);
            }
            if (jo.optInt("prePrice")==0){
                holder.tv_xianjia.setVisibility(View.GONE);
                holder.tv_yuanjia.getPaint().setFlags(0);
                holder.tv_yuanjia.setTextColor(mContext.getResources().getColor(R.color.colorE46006));
            }else {
                holder.tv_yuanjia.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG |Paint.ANTI_ALIAS_FLAG);
                holder.tv_xianjia.setVisibility(View.VISIBLE);
                holder.tv_xianjia.setTextColor(mContext.getResources().getColor(R.color.colorE46006));
                holder.tv_yuanjia.setTextColor(mContext.getResources().getColor(R.color.color999999));
            }
            holder.tv_xianjia.setText("￥"+ BigDecimalUtils.div(jo.optInt("prePrice")+"","100",2));
            holder.tv_yuanjia.setText("￥"+BigDecimalUtils.div(jo.optInt("price")+"","100",2)+"");


            if (jo.optInt("isSoldOut")==0){
                holder.rl_status.setVisibility(View.GONE);
                holder.fl_reduce.setEnabled(true);
                holder.rl_top.setEnabled(true);
                holder.fl_add.setEnabled(true);
            }else {
                holder.rl_status.setVisibility(View.VISIBLE);
                holder.fl_reduce.setEnabled(false);
                holder.rl_top.setEnabled(false);
                holder.fl_add.setEnabled(false);
            }

            String classifyName = jo.optString("classifyName");
            holder.headerTitle.setText(jo.optString("classifyName"));
            JSONArray js = jo.optJSONArray("cart");
         int count=0;
          int cartId=0;
           String condimentsId="";
            String specificationId=null;
                if (js!=null&&js.length()>0){
                    for (int i = 0; i < js.length(); i++) {
                        JSONObject listcount = js.optJSONObject(i);

                        count = count+listcount.optInt("count");
                        cartId = listcount.optInt("cartId");
                        specificationId=listcount.optString("specificationId");
                        condimentsId=listcount.optString("condimentsId");
                    }
                }

                holder.tv_number.setText(count + "");
//            }

//
            if (position != 0){
                JSONObject oldJo = getItem(position - 1);
                String oldClassifyName = oldJo.optString("classifyName");
                holder.headerTitle.setVisibility(classifyName.equals(oldClassifyName) ? View.GONE : View.VISIBLE);
                setChildGroup(position, !classifyName.equals(oldClassifyName));
            } else {
                holder.headerTitle.setVisibility(View.VISIBLE);
                setChildGroup(position, true);
            }
            int finalCount = count;
//
            if (count==0){
                holder.tv_number.setText("0");
                holder.fl_reduce.setVisibility(View.INVISIBLE);
                holder.tv_number.setVisibility(View.INVISIBLE);
            }else {
                holder.fl_reduce.setVisibility(View.VISIBLE);
                holder.tv_number.setVisibility(View.VISIBLE);
            }
//            count=jo.getCartCount();
            holder.rl_top.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (   jo.optInt("prePrice")!=0){
                        price = jo.optInt("prePrice");
                    }else {
                        price = jo.optInt("price");
                    }

                    mContext.startActivity(new Intent(mContext,ShopDetailsActivity.class).putExtra("commodityId",jo.optInt("commodityId")+"").putExtra("merchantid",merchantid).putExtra("img",jo.optString("img")).putExtra("shopname",shopname).putExtra("commodityname",jo.optString("commodityName")).putExtra("price",price+""));
                }
            });

            holder.fl_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    if (BtnUtils.isFastClick()) {
                        if (jo.optInt("prePrice") != 0) {
                            price = jo.optInt("prePrice");
                        } else {
                            price = jo.optInt("price");
                        }

//                        int size = finalCount;
//                        size++;
//
//
//                        JSONArray js = jo.optJSONArray("cart");
//
//                        if (js != null && js.length() > 0) {
//
//                            JSONObject listcount = js.optJSONObject(0);
//
//                            try {
//                                listcount.put("count", js.optJSONObject(0).optInt("count") + 1);
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                            holder.tv_number.setText(size + "");
//
//
//                            notifyDataSetChanged();

//                        }

//                        count++;

                        if (onAddCartrListener != null) {
                            onAddCartrListener.onAddShoppingCart(jo.optInt("commodityId") + "", "1", "", price + "", jo.optString("commodityName"), "", "", 0 + "");

                        }

//                    }
                }
            });

            String finalspecificationId = specificationId;
            String finalcondimentsId=condimentsId;
            holder.fl_reduce.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    if (BtnUtils.isFastClick()) {
                   int countcart= Integer.parseInt(holder.tv_number.getText().toString())-1;
//                        int size = finalCount;
//                        size--;

                        JSONArray js = jo.optJSONArray("cart");


                        if (jo.optInt("prePrice") != 0) {
                            price = jo.optInt("prePrice");
                        } else {
                            price = jo.optInt("price");
                        }
                        Log.e("BusinessAdapter", "onClick: " + js.length());
                        if (js.length() > 1) {
                            ToastUtils.show("不同规格商品需在购物车减购");
                        } else {

                            if (js != null && js.length() > 0) {

                                JSONObject listcount = js.optJSONObject(0);

                                try {
                                    listcount.put("count", js.optJSONObject(0).optInt("count") - 1);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
//                                holder.tv_number.setText(size + "");
//                                notifyDataSetChanged();
                            }
                            if (onAddCartrListener != null) {
//
                                Log.e("##", "onClick: "+finalspecificationId );
                                onAddCartrListener.onReduceShoppingCart(jo.optInt("commodityId") + "", "-1", "", price + "", jo.optString("commodityName"), finalcondimentsId, finalspecificationId + "", countcart + "");

                            }
                        }
//                    notifyDataSetChanged();

//                    }
                    }
//                }
            });
            holder.name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    UIHelper.startActivity(mContext, ShopDetailsActivity.class);

                }
            });
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (isGroup(position)) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public int getItemCount() {
        return jsa != null ? jsa.length() : 0;
    }

    class ItemHolder extends RecyclerView.ViewHolder {
        TextView titile;

        public ItemHolder(View itemView) {
            super(itemView);
        }
    }

    class ItemChildHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView tv_yueshou;
        TextView tv_xianjia;
        TextView tv_yuanjia;
        ImageView img_dianpu;
        FrameLayout fl_reduce;
        FrameLayout fl_add;
        TextView    tv_number;
        RelativeLayout rl_top;
        RelativeLayout rl_status;
        LinearLayoutCompat ll_number;
        TextView tv_buhuo;

        TextView headerTitle;
        public ItemChildHolder(View itemView) {
            super(itemView);
        }
    }

    public JSONObject getItem(int position) {
        JSONObject jo = jsa.optJSONObject(position);
        return jo;
    }
    public interface OnAddCartrListener {


        void onAddShoppingCart(String Id,String count,String prePrice,String price,String commodityName,String condimentsId,String cartId,String cartcount);


        void onReduceShoppingCart(String Id,String count,String prePrice,String price,String commodityName,String condimentsId,String cartId,String cartcount);

    }

    public void setOnGoodsOrderListener(OnAddCartrListener onAddCartrListener) {
        this.onAddCartrListener = onAddCartrListener;
    }

}